package com.lv.LvTourismModel.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aqgj.Attachment.bean.Attachment;
import com.aqgj.Attachment.dao.AttachmentDao;
import com.aqgj.Attachment.service.AttachmentManager;
import com.aqgj.User.bean.User;
import com.aqgj.User.dao.UserDao;
import com.lv.LvAttachmentComboOfTourismModel.bean.LvAttachmentComboOfTourismModel;
import com.lv.LvAttachmentComboOfTourismModel.dao.LvAttachmentComboOfTourismModelDao;
import com.lv.LvPriceComboOfTourismForModify.bean.LvPriceComboOfTourismForModify;
import com.lv.LvPriceComboOfTourismForModify.dao.LvPriceComboOfTourismForModifyDao;
import com.lv.LvPriceComboOfTourismModel.bean.LvPriceComboOfTourismModel;
import com.lv.LvPriceComboOfTourismModel.dao.LvPriceComboOfTourismModelDao;
import com.lv.LvTourismForSale.bean.LvTourismForSale;
import com.lv.LvTourismForSale.dao.LvTourismForSaleDao;
import com.lv.LvTourismForSale.service.LvTourismForSaleManager;
import com.lv.LvTourismModel.bean.LvTourismModel;
import com.lv.LvTourismModel.dao.LvTourismModelDao;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("LvTourismModel")
public class LvTourismModelManager {
    @Autowired
    LvTourismModelDao lvTourismModelDao;
    @Autowired
    LvPriceComboOfTourismModelDao lvPriceComboOfTourismModelDao;
    @Autowired
    LvPriceComboOfTourismForModifyDao lvPriceComboOfTourismForModifyDao;
    @Autowired
    AttachmentManager attachmentManager;
    @Autowired
    LvAttachmentComboOfTourismModelDao lvAttachmentComboOfTourismModelDao;
    @Autowired
    LvTourismForSaleDao lvTourismForSaleDao;
    @Autowired
    LvTourismForSaleManager lvTourismForSaleManager;
    @Autowired
    UserDao userDao;
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final int autoArangeClassesForSaleDays = 34;

    /**
     * 保存旅游模板但不生成在售旅游
     * @param lvTourismModel 旅游模板对象
     * @param priceComboData 价格套餐json字符串
     * @param pictureData 图片json字符串
     * @param attachmentData 附件字符串
     * @param user 用户对象
     * @param transport 公司对象
     * @param request
     * @return
     */
    public String save(LvTourismModel lvTourismModel, String priceComboData, String pictureData, String attachmentData, User user, ZtcTransport transport, HttpServletRequest request) {
        Date now = new Date();
        lvTourismModel.setAddTime(now);
        lvTourismModel.setFkAddUserId(user.getId());
        lvTourismModel.setFkAddUserName(user.getName());
        lvTourismModel.setStatus(0);
        lvTourismModel.setFkTransportId(transport.getId());
        lvTourismModelDao.save(lvTourismModel);
        JSONArray priceComboArray = JSON.parseArray(priceComboData);
        double minPrice = 1000000;
        for (int i = 0; i < priceComboArray.size(); i++) {
            JSONObject priceComboObject = priceComboArray.getJSONObject(i);
            String title = priceComboObject.getString("title");
            String comment = priceComboObject.getString("comment");
            String adultPrice = priceComboObject.getString("adultPrice");
            if (Double.parseDouble(adultPrice) < minPrice) {
                minPrice = Double.parseDouble(adultPrice);
            }
            String childPrice = priceComboObject.getString("childPrice");
            LvPriceComboOfTourismModel priceCombo = new LvPriceComboOfTourismModel();
            priceCombo.setTitle(title);
            priceCombo.setSequence(i);
            priceCombo.setComment(comment);
            priceCombo.setAdultPrice(new BigDecimal(adultPrice));
            priceCombo.setChildPrice(new BigDecimal(childPrice));
            priceCombo.setStatus(0);
            priceCombo.setAddTime(now);
            priceCombo.setFkAddUserId(user.getId());
            priceCombo.setFkTourismModelId(lvTourismModel.getId());
            lvPriceComboOfTourismModelDao.save(priceCombo);
        }
        JSONArray pictureArray = JSON.parseArray(pictureData);
        if (pictureArray != null) {
            for (int i = 0; i < pictureArray.size(); i++) {
                JSONObject object = pictureArray.getJSONObject(i);
                String attachmentId = object.getString("id");
                LvAttachmentComboOfTourismModel lvAttachmentComboOfTourismModel = new LvAttachmentComboOfTourismModel();
                lvAttachmentComboOfTourismModel.setSequence(i);
                lvAttachmentComboOfTourismModel.setFkTourismModelId(lvTourismModel.getId());
                lvAttachmentComboOfTourismModel.setComment("");
                lvAttachmentComboOfTourismModel.setFkAttachmentId(attachmentId);
                lvAttachmentComboOfTourismModel.setType(2);
                lvAttachmentComboOfTourismModel.setAddTime(now);
                lvAttachmentComboOfTourismModel.setFkAddUserId(user.getId());
                lvAttachmentComboOfTourismModel.setStatus(0);
                lvAttachmentComboOfTourismModelDao.save(lvAttachmentComboOfTourismModel);
                Attachment attachmentObject = attachmentManager.get(attachmentId);
                attachmentObject.setBusinessId(lvTourismModel.getId());
                attachmentObject.setWorkItem("rollingPicture");
                attachmentManager.update(attachmentObject);
            }
        }
        JSONArray attachmentArray = JSON.parseArray(attachmentData);
        for (int i = 0; i < attachmentArray.size(); i++) {
            JSONObject attachment = attachmentArray.getJSONObject(i);
            LvAttachmentComboOfTourismModel lvAttachmentComboOfTourismModel = new LvAttachmentComboOfTourismModel();
            lvAttachmentComboOfTourismModel.setSequence(i);
            lvAttachmentComboOfTourismModel.setFkTourismModelId(lvTourismModel.getId());
            if (attachment.getInteger("type") == 0) {
                lvAttachmentComboOfTourismModel.setComment(attachment.getString("text"));
                lvAttachmentComboOfTourismModel.setFkAttachmentId(attachment.getString("id"));
                lvAttachmentComboOfTourismModel.setType(0);
            } else {
                lvAttachmentComboOfTourismModel.setComment(attachment.getString("text"));
                lvAttachmentComboOfTourismModel.setFkAttachmentId("");
                lvAttachmentComboOfTourismModel.setType(1);
            }
            lvAttachmentComboOfTourismModel.setAddTime(now);
            lvAttachmentComboOfTourismModel.setFkAddUserId(user.getId());
            lvAttachmentComboOfTourismModel.setStatus(0);
            lvAttachmentComboOfTourismModelDao.save(lvAttachmentComboOfTourismModel);
            if (attachment.getInteger("type") == 0) {
                Attachment attachmentObject = attachmentManager.get(attachment.getString("id"));
                attachmentObject.setBusinessId(lvTourismModel.getId());
                attachmentObject.setFilePath(lvTourismModel.getId());
                attachmentObject.setWorkItem("attachmentPicture");
                attachmentManager.update(attachmentObject);
            }
        }
        return "1";
    }

    /**
     * 发布前修改
     * @param lvTourismModel 旅游模板对象
     * @param priceComboData 价格套餐json字符串
     * @param pictureData 图片json字符串
     * @param attachmentData 附件json字符串
     * @param user 用户对象
     * @return
     */
    public String update(LvTourismModel lvTourismModel, String priceComboData, String pictureData, String attachmentData, User user) {
        Date now=new Date();
        lvPriceComboOfTourismModelDao.delete(null,lvTourismModel.getId());
        BigDecimal minPrice=new BigDecimal(1000000);
        JSONArray priceComboArray = JSON.parseArray(priceComboData);
        if (priceComboArray != null) {
            for (int i = 0; i < priceComboArray.size(); i++) {
                JSONObject object = priceComboArray.getJSONObject(i);
                LvPriceComboOfTourismModel priceCombo = new LvPriceComboOfTourismModel();
                priceCombo.setTitle(object.getString("title"));
                priceCombo.setSequence(i);
                priceCombo.setComment(object.getString("comment"));
                BigDecimal price=new BigDecimal(object.getString("adultPrice"));
                if(price.compareTo(minPrice)<0){
                    minPrice=price;
                }
                priceCombo.setAdultPrice(price);
                priceCombo.setChildPrice(new BigDecimal(object.getString("childPrice")));
                priceCombo.setStatus(0);
                priceCombo.setAddTime(now);
                priceCombo.setFkAddUserId(user.getId());
                priceCombo.setFkTourismModelId(lvTourismModel.getId());
                lvPriceComboOfTourismModelDao.update(priceCombo);
            }
        }
        String updatePicture=updatePicture(lvTourismModel.getId(),pictureData,user.getId());
        if("0".equals(updatePicture)){
            return "0";
        }
        String updateAttachment=updateAttachment(lvTourismModel.getId(),attachmentData,user.getId());
        if("0".equals(updateAttachment)){
            return "0";
        }
        LvTourismModel lvTourismModelBean=lvTourismModelDao.get(lvTourismModel.getId());
        lvTourismModelBean.setTourismName(lvTourismModel.getTourismName());
        lvTourismModelBean.setStartSiteName(lvTourismModel.getStartSiteName());
        lvTourismModelBean.setStartSiteAddress(lvTourismModel.getStartSiteAddress());
        lvTourismModelBean.setTerminalSiteName(lvTourismModel.getTerminalSiteName());
        lvTourismModelBean.setTerminalSiteAddress(lvTourismModel.getTerminalSiteAddress());
        lvTourismModelBean.setTitle(lvTourismModel.getTitle());
        lvTourismModelBean.setAdultSeatNumber(lvTourismModel.getAdultSeatNumber());
        lvTourismModelBean.setChildSeatNumber(lvTourismModel.getChildSeatNumber());
        lvTourismModelBean.setAllowIncreaseGuestRoom(lvTourismModel.getAllowIncreaseGuestRoom());
        lvTourismModelBean.setReasonOfAllowIncreaseGuestRoom(lvTourismModel.getReasonOfAllowIncreaseGuestRoom());
        lvTourismModelBean.setGuestRoomPrice(lvTourismModel.getGuestRoomPrice());
        lvTourismModelBean.setModifyTime(now);
        lvTourismModelBean.setFkModifyUserId(user.getId());
        String updateModel=lvTourismModelDao.update(lvTourismModelBean);
        if("0".equals(updateModel)){
            return "0";
        }
        return "1";
    }

    /**
     * 发布后修改
     * @param lvTourismModel 旅游模板对象
     * @param priceComboData 价格套餐json字符串
     * @param pictureData 图片json字符串
     * @param attachmentData 附件json字符串
     * @param user 用户对象
     * @return
     */
    public String updateSell(LvTourismModel lvTourismModel,String priceComboData,String pictureData,String attachmentData,User user) {
        Date now=new Date();
        BigDecimal minPrice=new BigDecimal(1000000);
        JSONArray priceComboArray = JSON.parseArray(priceComboData);
        if (priceComboArray != null) {
            for (int i = 0; i < priceComboArray.size(); i++) {
                JSONObject object = priceComboArray.getJSONObject(i);
                LvPriceComboOfTourismModel priceCombo = new LvPriceComboOfTourismModel();
                priceCombo.setTitle(object.getString("title"));
                priceCombo.setSequence(i);
                priceCombo.setComment(object.getString("comment"));
                BigDecimal price=new BigDecimal(object.getString("adultPrice"));
                if(price.compareTo(minPrice)<0){
                    minPrice=price;
                }
                priceCombo.setAdultPrice(price);
                priceCombo.setChildPrice(new BigDecimal(object.getString("childPrice")));
                priceCombo.setStatus(0);
                priceCombo.setAddTime(now);
                priceCombo.setFkAddUserId(user.getId());
                priceCombo.setFkTourismModelId(lvTourismModel.getId());
                lvPriceComboOfTourismModelDao.update(priceCombo);
            }
        }
        String updatePicture=updatePicture(lvTourismModel.getId(),pictureData,user.getId());
        if("0".equals(updatePicture)){
            return "0";
        }
        String updateAttachment=updateAttachment(lvTourismModel.getId(),attachmentData,user.getId());
        if("0".equals(updateAttachment)){
            return "0";
        }
        LvTourismModel lvTourismModelBean=lvTourismModelDao.get(lvTourismModel.getId());
        lvTourismModelBean.setTourismName(lvTourismModel.getTourismName());
        lvTourismModelBean.setStartSiteName(lvTourismModel.getStartSiteName());
        lvTourismModelBean.setStartSiteAddress(lvTourismModel.getStartSiteAddress());
        lvTourismModelBean.setTerminalSiteName(lvTourismModel.getTerminalSiteName());
        lvTourismModelBean.setTerminalSiteAddress(lvTourismModel.getTerminalSiteAddress());
        lvTourismModelBean.setTitle(lvTourismModel.getTitle());
        lvTourismModelBean.setAdultSeatNumber(lvTourismModel.getAdultSeatNumber());
        lvTourismModelBean.setChildSeatNumber(lvTourismModel.getChildSeatNumber());
        lvTourismModelBean.setAllowIncreaseGuestRoom(lvTourismModel.getAllowIncreaseGuestRoom());
        lvTourismModelBean.setReasonOfAllowIncreaseGuestRoom(lvTourismModel.getReasonOfAllowIncreaseGuestRoom());
        lvTourismModelBean.setGuestRoomPrice(lvTourismModel.getGuestRoomPrice());
        lvTourismModelBean.setModifyTime(now);
        lvTourismModelBean.setFkModifyUserId(user.getId());
        String updateModel=lvTourismModelDao.update(lvTourismModelBean);
        if("0".equals(updateModel)){
            return "0";
        }
        List<LvTourismForSale> lvTourismForSaleList=lvTourismForSaleManager.search(lvTourismModel.getId(),lvTourismModel.getApplicationStartDate(),null);
        for(int i=0;i<lvTourismForSaleList.size();i++){
            LvTourismForSale lvTourismForSale=lvTourismForSaleList.get(i);
            if(lvTourismForSale.getSaledAdultSeatNumber()>0){
                if(lvTourismForSale.getStatus()==0){
                    if(lvTourismModel.getAdultSeatNumber()-lvTourismForSale.getSaledAdultSeatNumber()>0
                            &&lvTourismModel.getChildSeatNumber()-lvTourismForSale.getSaledChildSeatNumber()>0){
                        lvTourismForSale.setAdultSeatNumber(lvTourismModel.getAdultSeatNumber());
                        lvTourismForSale.setChildSeatNumber(lvTourismModel.getChildSeatNumber());
                        lvTourismForSale.setMinPrice(minPrice);
                        lvTourismForSale.setIsModifyPriceCombo(lvTourismModel.getAllowIncreaseGuestRoom());
                        lvTourismForSale.setModifyTime(now);
                        lvTourismForSale.setFkModifyUserId(user.getId());
                        String updateResult=lvTourismForSaleDao.update(lvTourismForSale);
                        if("0".equals(updateResult)){
                            return "0";
                        }
                    }else{
                        lvTourismForSale.setMinPrice(minPrice);
                        lvTourismForSale.setIsModifyPriceCombo(lvTourismModel.getAllowIncreaseGuestRoom());
                        lvTourismForSale.setModifyTime(now);
                        lvTourismForSale.setFkModifyUserId(user.getId());
                        String updateResult=lvTourismForSaleDao.update(lvTourismForSale);
                        if("0".equals(updateResult)){
                            return "0";
                        }
                    }
                }
            }else{
                if(lvTourismForSale.getStatus()==0) {
                    lvTourismForSale.setAdultSeatNumber(lvTourismModel.getAdultSeatNumber());
                    lvTourismForSale.setChildSeatNumber(lvTourismModel.getChildSeatNumber());
                    lvTourismForSale.setMinPrice(minPrice);
                    lvTourismForSale.setIsModifyPriceCombo(lvTourismModel.getAllowIncreaseGuestRoom());
                    lvTourismForSale.setModifyTime(now);
                    lvTourismForSale.setFkModifyUserId(user.getId());
                    String updateResult = lvTourismForSaleDao.update(lvTourismForSale);
                    if ("0".equals(updateResult)) {
                        return "0";
                    }
                }
            }
        }
        return "1";
    }

    /**
     * 发布前生成在售旅游
     * @param lvTourismModel 旅游模板对象
     * @param user 用户对象
     * @return
     */
    public String generate(LvTourismModel lvTourismModel, User user) {
        String sql = "delete from lv_tourism_for_sale where fk_tourism_model_id='" + lvTourismModel.getId() + "'";
        lvTourismForSaleDao.delete(sql);
        Date now = new Date();
        LvTourismModel lvTourismModelBean = lvTourismModelDao.get(lvTourismModel.getId());
        if (lvTourismModel.getSchedulingMode() == 0) {
            lvTourismModelBean.setSchedulingMode(0);
            if (lvTourismModel.getSchedulingRule() == 0) {
                lvTourismModelBean.setSchedulingRule(0);
                lvTourismModelBean.setSchedulingRuleDay(lvTourismModel.getSchedulingRuleDay());
                lvTourismModelBean.setSchedulingRuleDaysOfWeek(null);
                lvTourismModelBean.setSchedulingRuleDaysOfMonth(null);
                lvTourismModelBean.setSchedulingModeSelectDates(null);
            }
            if (lvTourismModel.getSchedulingRule() == 1) {
                lvTourismModelBean.setSchedulingRule(1);
                lvTourismModelBean.setSchedulingRuleDay(null);
                lvTourismModelBean.setSchedulingRuleDaysOfWeek(lvTourismModel.getSchedulingRuleDaysOfWeek());
                lvTourismModelBean.setSchedulingRuleDaysOfMonth(null);
                lvTourismModelBean.setSchedulingModeSelectDates(null);
            }
            if (lvTourismModel.getSchedulingRule() == 2) {
                lvTourismModelBean.setSchedulingRule(2);
                lvTourismModelBean.setSchedulingRuleDay(null);
                lvTourismModelBean.setSchedulingRuleDaysOfWeek(null);
                lvTourismModelBean.setSchedulingRuleDaysOfMonth(lvTourismModel.getSchedulingRuleDaysOfMonth());
                lvTourismModelBean.setSchedulingModeSelectDates(null);
            }
            lvTourismModelBean.setPreSaleDays(lvTourismModel.getPreSaleDays());
        } else {
            lvTourismModelBean.setSchedulingMode(1);
            lvTourismModelBean.setSchedulingRuleDay(null);
            lvTourismModelBean.setSchedulingRuleDaysOfWeek(null);
            lvTourismModelBean.setSchedulingRuleDaysOfMonth(null);
            lvTourismModelBean.setSchedulingModeSelectDates(lvTourismModel.getSchedulingModeSelectDates());
        }
        lvTourismModelBean.setApplicationStartDate(lvTourismModel.getApplicationStartDate());
        String result = lvTourismModelDao.update(lvTourismModelBean);
        if ("0".equals(result)) {
            return "0";
        }
        List<Date> serverAllDates = new ArrayList<>();
        if (lvTourismModelBean.getSchedulingMode() == 0) {
            int preSaleDays = lvTourismModelBean.getPreSaleDays();
            Date startDate = lvTourismModelBean.getApplicationStartDate();
            if (lvTourismModelBean.getSchedulingRule() == 0) {
                int intDayFrequencyType = lvTourismModelBean.getSchedulingRuleDay() + 1;
                for (int i = 0; i < preSaleDays; i = i + intDayFrequencyType) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    calendar.add(Calendar.DATE, i);
                    if (lvTourismModelBean.getAutoArrangeEndDate() != null && !"".equals(lvTourismModelBean.getAutoArrangeEndDate())) {
                        if (calendar.getTime().getTime() < lvTourismModelBean.getAutoArrangeEndDate().getTime()) {
                            serverAllDates.add(calendar.getTime());
                        }
                    } else {
                        serverAllDates.add(calendar.getTime());
                    }
                }
            }
            if (lvTourismModelBean.getSchedulingRule() == 1) {
                String weekDayInfo = lvTourismModelBean.getSchedulingRuleDaysOfWeek();
                String[] weekDays = weekDayInfo.split(",");
                for (int i = 0; i < preSaleDays; i++) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    calendar.add(Calendar.DATE, i);
                    if (lvTourismModelBean.getAutoArrangeEndDate() != null && !"".equals(lvTourismModelBean.getAutoArrangeEndDate())) {
                        if (calendar.getTime().getTime() < lvTourismModelBean.getAutoArrangeEndDate().getTime()) {
                            for (String day : weekDays) {
                                if (!"".equals(day)) {
                                    if (Integer.parseInt(day) == calendar.get(Calendar.DAY_OF_WEEK) - 1) {
                                        serverAllDates.add(calendar.getTime());
                                    }
                                }
                            }
                        }
                    } else {
                        for (String day : weekDays) {
                            if (!"".equals(day)) {
                                if (Integer.parseInt(day) == calendar.get(Calendar.DAY_OF_WEEK) - 1) {
                                    serverAllDates.add(calendar.getTime());
                                }
                            }
                        }
                    }
                }
            }
            if (lvTourismModelBean.getSchedulingRule() == 2) {
                String monthDayInfo = lvTourismModelBean.getSchedulingRuleDaysOfMonth();
                String[] monthDays = monthDayInfo.split(",");
                for (int i = 0; i < preSaleDays; i++) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    calendar.add(Calendar.DATE, i);
                    if (lvTourismModelBean.getAutoArrangeEndDate() != null && !"".equals(lvTourismModelBean.getAutoArrangeEndDate())) {
                        if (calendar.getTime().getTime() < lvTourismModelBean.getAutoArrangeEndDate().getTime()) {
                            for (String day : monthDays) {
                                if (!"".equals(day)) {
                                    if (Integer.parseInt(day) == calendar.get(Calendar.DATE)) {
                                        serverAllDates.add(calendar.getTime());
                                    }
                                }
                            }
                        }
                    } else {
                        for (String day : monthDays) {
                            if (!"".equals(day)) {
                                if (Integer.parseInt(day) == calendar.get(Calendar.DATE)) {
                                    serverAllDates.add(calendar.getTime());
                                }
                            }
                        }
                    }
                }
            }
        } else {
            String selectDates = lvTourismModelBean.getSchedulingModeSelectDates();
            String[] dates = selectDates.split(",");
            for (int i = 0; i < dates.length; i++) {
                String date = dates[i];
                try {
                    serverAllDates.add(DATE_FORMAT.parse(date));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        List<LvPriceComboOfTourismModel> lvPriceComboOfTourismModelList = lvPriceComboOfTourismModelDao.findBy("fkTourismModelId", lvTourismModelBean.getId());
        BigDecimal minPrice = new BigDecimal(1000000);
        for (int i = 0; i < lvPriceComboOfTourismModelList.size(); i++) {
            LvPriceComboOfTourismModel lvPriceComboOfTourismModel = lvPriceComboOfTourismModelList.get(i);
            if (lvPriceComboOfTourismModel.getAdultPrice().compareTo(minPrice) < 0) {
                minPrice = lvPriceComboOfTourismModel.getAdultPrice();
            }
        }
        for (int i = 0; i < serverAllDates.size(); i++) {
            Date serverDate = serverAllDates.get(i);
            LvTourismForSale lvTourismForSale = new LvTourismForSale();
            lvTourismForSale.setAdultSeatNumber(lvTourismModelBean.getAdultSeatNumber());
            lvTourismForSale.setChildSeatNumber(lvTourismModelBean.getChildSeatNumber());
            lvTourismForSale.setSaledAdultSeatNumber(0);
            lvTourismForSale.setSaledChildSeatNumber(0);
            lvTourismForSale.setServerDate(serverDate);
            lvTourismForSale.setStatus(0);
            lvTourismForSale.setMinPrice(minPrice);
            lvTourismForSale.setIsModifyPriceCombo(lvTourismModelBean.getAllowIncreaseGuestRoom());
            lvTourismForSale.setAddTime(now);
            lvTourismForSale.setFkAddUserId(user.getId());
            lvTourismForSale.setFkTourismModelId(lvTourismModelBean.getId());
            lvTourismForSale.setAllowIncreaseGuestRoom(lvTourismModelBean.getAllowIncreaseGuestRoom());
            lvTourismForSale.setGuestRoomPrice(lvTourismModelBean.getGuestRoomPrice());
            lvTourismForSale.setIsModifyPriceCombo(0);
            lvTourismForSaleDao.update(lvTourismForSale);
        }
        String listResult = "0";
        List<LvTourismForSale> lvTourismForSaleShowList = lvTourismForSaleManager.search(lvTourismModelBean.getId(), null, null);
        if (lvTourismForSaleShowList != null && lvTourismForSaleShowList.size() > 0) {
            listResult = "[";
            int count = 0;
            for (int i = 0; i < lvTourismForSaleShowList.size(); i++) {
                LvTourismForSale lvTourismForSale = lvTourismForSaleShowList.get(i);
                if (count == lvTourismForSaleShowList.size()) {
                    listResult += "{\"id\":\"" + (lvTourismForSale.getId() == null ? "" : lvTourismForSale.getId())
                            + "\"," + "\"price\":\"" + (lvTourismForSale.getMinPrice() == null ? "" : lvTourismForSale.getMinPrice())
                            + "\"," + "\"status\":\"" + (lvTourismForSale.getStatus() == null ? "" : lvTourismForSale.getStatus() == 0 ? 1 : 3)
                            + "\"," + "\"serverDate\":\"" + (lvTourismForSale.getServerDate() == null ? "" : DATE_FORMAT.format(lvTourismForSale.getServerDate())) + "\"},";
                } else {
                    listResult += "{\"id\":\"" + (lvTourismForSale.getId() == null ? "" : lvTourismForSale.getId())
                            + "\"," + "\"price\":\"" + (lvTourismForSale.getMinPrice() == null ? "" : lvTourismForSale.getMinPrice())
                            + "\"," + "\"status\":\"" + (lvTourismForSale.getStatus() == null ? "" : lvTourismForSale.getStatus() == 0 ? 1 : 3)
                            + "\"," + "\"serverDate\":\"" + (lvTourismForSale.getServerDate() == null ? "" : DATE_FORMAT.format(lvTourismForSale.getServerDate())) + "\"}";
                }
                count++;
            }
            listResult += "]";
        }
        return listResult;
    }
    /**
     * 发布后生成在售旅游
     * @param lvTourismModel 旅游模板对象
     * @param user 用户对象
     * @return
     */
    public String generateSell(LvTourismModel lvTourismModel,User user) {
        Date now=new Date();
        LvTourismModel lvTourismModelBean = lvTourismModelDao.get(lvTourismModel.getId());
        if (lvTourismModel.getSchedulingMode() == 0) {
            lvTourismModelBean.setSchedulingMode(0);
            if (lvTourismModel.getSchedulingRule() == 0) {
                lvTourismModelBean.setSchedulingRule(0);
                lvTourismModelBean.setSchedulingRuleDay(lvTourismModel.getSchedulingRuleDay());
                lvTourismModelBean.setSchedulingRuleDaysOfWeek(null);
                lvTourismModelBean.setSchedulingRuleDaysOfMonth(null);
                lvTourismModelBean.setSchedulingModeSelectDates(null);
            }
            if (lvTourismModel.getSchedulingRule() == 1) {
                lvTourismModelBean.setSchedulingRule(1);
                lvTourismModelBean.setSchedulingRuleDay(null);
                lvTourismModelBean.setSchedulingRuleDaysOfWeek(lvTourismModel.getSchedulingRuleDaysOfWeek());
                lvTourismModelBean.setSchedulingRuleDaysOfMonth(null);
                lvTourismModelBean.setSchedulingModeSelectDates(null);
            }
            if (lvTourismModel.getSchedulingRule() == 2) {
                lvTourismModelBean.setSchedulingRule(2);
                lvTourismModelBean.setSchedulingRuleDay(null);
                lvTourismModelBean.setSchedulingRuleDaysOfWeek(null);
                lvTourismModelBean.setSchedulingRuleDaysOfMonth(lvTourismModel.getSchedulingRuleDaysOfMonth());
                lvTourismModelBean.setSchedulingModeSelectDates(null);
            }
            lvTourismModelBean.setPreSaleDays(lvTourismModel.getPreSaleDays());
        } else {
            lvTourismModelBean.setSchedulingMode(1);
            lvTourismModelBean.setSchedulingRuleDay(null);
            lvTourismModelBean.setSchedulingRuleDaysOfWeek(null);
            lvTourismModelBean.setSchedulingRuleDaysOfMonth(null);
            lvTourismModelBean.setSchedulingModeSelectDates(lvTourismModel.getSchedulingModeSelectDates());
        }
        lvTourismModelBean.setApplicationStartDate(lvTourismModel.getApplicationStartDate());
        String result = lvTourismModelDao.update(lvTourismModelBean);
        if ("0".equals(result)) {
            return "0";
        }
        List<Date> serverAllDates = new ArrayList<>();
        Date startDate =lvTourismModel.getApplicationStartDate();
        serverAllDates.add(startDate);
        if (lvTourismModel.getSchedulingMode()==0) {
            if(lvTourismModel.getSchedulingRule()==0){
                int intDayFrequencyType = lvTourismModel.getSchedulingRuleDay()+1;
                for (int i = 1; i <= autoArangeClassesForSaleDays; i = i + intDayFrequencyType) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    calendar.add(Calendar.DATE, i);
                    if(lvTourismModel.getAutoArrangeEndDate()!=null&&!"".equals(lvTourismModel.getAutoArrangeEndDate())){
                        if(calendar.getTime().getTime()<lvTourismModel.getAutoArrangeEndDate().getTime()){
                            serverAllDates.add(calendar.getTime());
                        }
                    }else{
                        serverAllDates.add(calendar.getTime());
                    }
                }
            }
            if(lvTourismModel.getSchedulingRule()==1){
                String weekDayInfo=lvTourismModel.getSchedulingRuleDaysOfWeek();
                String[] weekDays = weekDayInfo.substring(1,weekDayInfo.length()-1).split(",");
                for (int i = 1; i <= autoArangeClassesForSaleDays; i++) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    calendar.add(Calendar.DATE, i);
                    if(lvTourismModel.getAutoArrangeEndDate()!=null&&!"".equals(lvTourismModel.getAutoArrangeEndDate())){
                        if(calendar.getTime().getTime()<lvTourismModel.getAutoArrangeEndDate().getTime()){
                            for (String day : weekDays) {
                                if (!"".equals(day)) {
                                    if (Integer.parseInt(day) == calendar.get(Calendar.DAY_OF_WEEK) - 1) {
                                        serverAllDates.add(calendar.getTime());
                                    }
                                }
                            }
                        }
                    }else{
                        for (String day : weekDays) {
                            if (!"".equals(day)) {
                                if (Integer.parseInt(day) == calendar.get(Calendar.DAY_OF_WEEK) - 1) {
                                    serverAllDates.add(calendar.getTime());
                                }
                            }
                        }
                    }
                }
            }
            if(lvTourismModel.getSchedulingRule()==2) {
                String monthDayInfo = lvTourismModel.getSchedulingRuleDaysOfMonth();
                String[] monthDays = monthDayInfo.substring(1, monthDayInfo.length() - 1).split(",");
                for (int i = 1; i <= autoArangeClassesForSaleDays; i++) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    calendar.add(Calendar.DATE, i);
                    if (lvTourismModel.getAutoArrangeEndDate() != null && !"".equals(lvTourismModel.getAutoArrangeEndDate())) {
                        if (calendar.getTime().getTime() < lvTourismModel.getAutoArrangeEndDate().getTime()) {
                            for (String day : monthDays) {
                                if (!"".equals(day)) {
                                    if (Integer.parseInt(day) == calendar.get(Calendar.DATE)) {
                                        serverAllDates.add(calendar.getTime());
                                    }
                                }
                            }
                        }
                    } else {
                        for (String day : monthDays) {
                            if (!"".equals(day)) {
                                if (Integer.parseInt(day) == calendar.get(Calendar.DATE)) {
                                    serverAllDates.add(calendar.getTime());
                                }
                            }
                        }
                    }
                }
            }
        } else {
            String selectDates=lvTourismModel.getSchedulingModeSelectDates();
            selectDates = selectDates.substring(1, selectDates.length() - 1);
            String[] dates = selectDates.split(",");
            for (int i = 0; i < dates.length; i++) {
                String date = dates[i];
                date = date.substring(1, date.length() - 1);
                try {
                    serverAllDates.add(DATE_FORMAT.parse(date));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        List<LvPriceComboOfTourismModel> lvPriceComboOfTourismModelList = lvPriceComboOfTourismModelDao.findBy("fkTourismModelId", lvTourismModelBean.getId());
        BigDecimal minPrice = new BigDecimal(1000000);
        for (int i = 0; i < lvPriceComboOfTourismModelList.size(); i++) {
            LvPriceComboOfTourismModel lvPriceComboOfTourismModel = lvPriceComboOfTourismModelList.get(i);
            if (lvPriceComboOfTourismModel.getAdultPrice().compareTo(minPrice) < 0) {
                minPrice = lvPriceComboOfTourismModel.getAdultPrice();
            }
        }
        Date endDate=serverAllDates.get(serverAllDates.size()-1);
        int count=0;
        while(true){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            calendar.add(Calendar.DATE, count);
            if(calendar.getTime().getTime()>endDate.getTime()){
                break;
            }
            boolean isToday=false;
            for (int i = 0; i < serverAllDates.size(); i++) {
                Date serverDate = serverAllDates.get(i);
                if(serverDate.getTime()==calendar.getTime().getTime()){
                    isToday=true;
                }
            }
            Date serverDate=calendar.getTime();
            String sql = "select * from lv_tourism_for_sale where 1=1 and fk_tourism_model_id='" + lvTourismModelBean.getId() + "' and server_date='"+DATE_FORMAT.format(serverDate)+"'";
            List<LvTourismForSale> lvTourismForSaleList=lvTourismForSaleDao.search(sql);
            if(isToday){
                if(lvTourismForSaleList!=null&&lvTourismForSaleList.size()>0){
                    LvTourismForSale lvTourismForSale=lvTourismForSaleList.get(0);
                    if(lvTourismForSale.getSaledAdultSeatNumber()>0){
                        if(lvTourismForSale.getStatus()==0){
                            if(lvTourismModel.getAdultSeatNumber()-lvTourismForSale.getSaledAdultSeatNumber()>0
                                    &&lvTourismModel.getChildSeatNumber()-lvTourismForSale.getSaledChildSeatNumber()>0){
                                lvTourismForSale.setAdultSeatNumber(lvTourismModel.getAdultSeatNumber());
                                lvTourismForSale.setChildSeatNumber(lvTourismModel.getChildSeatNumber());
                                lvTourismForSale.setMinPrice(minPrice);
                                lvTourismForSale.setIsModifyPriceCombo(lvTourismModel.getAllowIncreaseGuestRoom());
                                lvTourismForSale.setModifyTime(now);
                                lvTourismForSale.setFkModifyUserId(user.getId());
                                String updateResult=lvTourismForSaleDao.update(lvTourismForSale);
                                if("0".equals(updateResult)){
                                    return "0";
                                }
                            }else{
                                lvTourismForSale.setMinPrice(minPrice);
                                lvTourismForSale.setIsModifyPriceCombo(lvTourismModel.getAllowIncreaseGuestRoom());
                                lvTourismForSale.setModifyTime(now);
                                lvTourismForSale.setFkModifyUserId(user.getId());
                                String updateResult=lvTourismForSaleDao.update(lvTourismForSale);
                                if("0".equals(updateResult)){
                                    return "0";
                                }
                            }
                        }
                    }else{
                        sql = "delete from lv_tourism_for_sale where 1=1 and id='" + lvTourismForSale.getId() + "'";
                        lvTourismForSaleDao.delete(sql);
                        LvTourismForSale tourismForSale = new LvTourismForSale();
                        tourismForSale.setAdultSeatNumber(lvTourismModel.getAdultSeatNumber());
                        tourismForSale.setChildSeatNumber(lvTourismModel.getChildSeatNumber());
                        tourismForSale.setSaledAdultSeatNumber(0);
                        tourismForSale.setSaledChildSeatNumber(0);
                        tourismForSale.setServerDate(serverDate);
                        tourismForSale.setStatus(0);
                        tourismForSale.setMinPrice(minPrice);
                        tourismForSale.setIsModifyPriceCombo(lvTourismModel.getAllowIncreaseGuestRoom());
                        tourismForSale.setAddTime(now);
                        tourismForSale.setFkAddUserId(user.getId());
                        tourismForSale.setFkTourismModelId(lvTourismModel.getId());
                        tourismForSale.setAllowIncreaseGuestRoom(lvTourismModel.getAllowIncreaseGuestRoom());
                        tourismForSale.setGuestRoomPrice(lvTourismModel.getGuestRoomPrice());
                        tourismForSale.setFkTransportId(lvTourismModel.getFkTransportId());
                        tourismForSale.setIsModifyPriceCombo(0);
                        lvTourismForSaleDao.update(tourismForSale);
                    }
                }else{
                    LvTourismForSale lvTourismForSale = new LvTourismForSale();
                    lvTourismForSale.setAdultSeatNumber(lvTourismModel.getAdultSeatNumber());
                    lvTourismForSale.setChildSeatNumber(lvTourismModel.getChildSeatNumber());
                    lvTourismForSale.setSaledAdultSeatNumber(0);
                    lvTourismForSale.setSaledChildSeatNumber(0);
                    lvTourismForSale.setServerDate(serverDate);
                    lvTourismForSale.setStatus(0);
                    lvTourismForSale.setMinPrice(minPrice);
                    lvTourismForSale.setIsModifyPriceCombo(lvTourismModel.getAllowIncreaseGuestRoom());
                    lvTourismForSale.setAddTime(now);
                    lvTourismForSale.setFkAddUserId(user.getId());
                    lvTourismForSale.setFkTourismModelId(lvTourismModel.getId());
                    lvTourismForSale.setAllowIncreaseGuestRoom(lvTourismModel.getAllowIncreaseGuestRoom());
                    lvTourismForSale.setGuestRoomPrice(lvTourismModel.getGuestRoomPrice());
                    lvTourismForSale.setFkTransportId(lvTourismModel.getFkTransportId());
                    lvTourismForSale.setIsModifyPriceCombo(0);
                    lvTourismForSaleDao.update(lvTourismForSale);
                }
            }else{
                if(lvTourismForSaleList!=null&&lvTourismForSaleList.size()>0){
                    LvTourismForSale lvTourismForSale=lvTourismForSaleList.get(0);
                    if(lvTourismForSale.getSaledAdultSeatNumber()==0){
                        sql = "delete from lv_tourism_for_sale where 1=1 and id='" + lvTourismForSale.getId() + "'";
                        lvTourismForSaleDao.delete(sql);
                    }
                }
            }
            count++;
        }
        String sql = "select * from lv_tourism_for_sale where 1=1 and fk_tourism_model_id='" + lvTourismModel.getId() + "' and server_date>'"+DATE_FORMAT.format(endDate)+"'";
        List<LvTourismForSale> lvTourismForSaleList=lvTourismForSaleDao.search(sql);
        for(int i=0;i<lvTourismForSaleList.size();i++){
            LvTourismForSale lvTourismForSale=lvTourismForSaleList.get(i);
            lvTourismForSale.setStatus(1);
            lvTourismForSale.setModifyTime(now);
            lvTourismForSale.setFkModifyUserId(user.getId());
            result=lvTourismForSaleDao.update(lvTourismForSale);
            if("0".equals(result)){
                return "0";
            }
        }
        return "1";
    }

    /**
     * 根据id获取旅游模板及其价格套餐，滚动图片，附件
     * @param id 旅游模板id
     * @return
     */
    public HashMap<String, Object> getById(String id) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        LvTourismModel lvTourismModel = lvTourismModelDao.get(id);
        result.put("lvTourismModel", lvTourismModel);
        String addUserId=lvTourismModel.getFkAddUserId();
        if(addUserId==null||"".equals(addUserId)){
            addUserId="-1";
        }
        User addUser=userDao.get(addUserId);
        result.put("addUser",addUser);
        String modifyUserId=lvTourismModel.getFkModifyUserId();
        if(modifyUserId==null||"".equals(modifyUserId)){
            modifyUserId="-1";
        }
        User modifyUser=userDao.get(modifyUserId);
        result.put("modifyUser",modifyUser);
        List<LvPriceComboOfTourismModel> lvPriceComboOfTourismModelList = lvPriceComboOfTourismModelDao.findBy("fkTourismModelId", id);
        int count = 0;
        String priceComboValue = "[";
        for (int i = 0; i < lvPriceComboOfTourismModelList.size(); i++) {
            LvPriceComboOfTourismModel lvPriceComboOfTourismModel = lvPriceComboOfTourismModelList.get(i);
            if (count == lvPriceComboOfTourismModelList.size()) {
                priceComboValue += "{\"title\":\"" + (lvPriceComboOfTourismModel.getTitle() == null ? "" : lvPriceComboOfTourismModel.getTitle())
                        + "\"," + "\"comment\":\"" + (lvPriceComboOfTourismModel.getComment() == null ? "" : lvPriceComboOfTourismModel.getComment())
                        + "\"," + "\"sequence\":\"" + (lvPriceComboOfTourismModel.getSequence() == null ? "" : lvPriceComboOfTourismModel.getSequence())
                        + "\"," + "\"adultPrice\":\"" + (lvPriceComboOfTourismModel.getAdultPrice() == null ? "" : lvPriceComboOfTourismModel.getAdultPrice())
                        + "\"," + "\"childPrice\":\"" + (lvPriceComboOfTourismModel.getChildPrice() == null ? "" : lvPriceComboOfTourismModel.getChildPrice()) + "\"},";
            } else {
                priceComboValue += "{\"title\":\"" + (lvPriceComboOfTourismModel.getTitle() == null ? "" : lvPriceComboOfTourismModel.getTitle())
                        + "\"," + "\"comment\":\"" + (lvPriceComboOfTourismModel.getComment() == null ? "" : lvPriceComboOfTourismModel.getComment())
                        + "\"," + "\"sequence\":\"" + (lvPriceComboOfTourismModel.getSequence() == null ? "" : lvPriceComboOfTourismModel.getSequence())
                        + "\"," + "\"adultPrice\":\"" + (lvPriceComboOfTourismModel.getAdultPrice() == null ? "" : lvPriceComboOfTourismModel.getAdultPrice())
                        + "\"," + "\"childPrice\":\"" + (lvPriceComboOfTourismModel.getChildPrice() == null ? "" : lvPriceComboOfTourismModel.getChildPrice()) + "\"}";
            }
            count++;
        }
        priceComboValue += "]";
        result.put("priceComboData", JSON.parseArray(priceComboValue));
        List<LvAttachmentComboOfTourismModel> attachmentList = lvAttachmentComboOfTourismModelDao.findBy("fkTourismModelId", id, "type", "2");
        String pictureValue = "[";
        for (int i = 0; i < attachmentList.size(); i++) {
            LvAttachmentComboOfTourismModel attachment = attachmentList.get(i);
            if (i != attachmentList.size() - 1) {
                pictureValue += "{\"id\":\"" + attachment.getFkAttachmentId() + "\"},";
            } else {
                pictureValue += "{\"id\":\"" + attachment.getFkAttachmentId() + "\"}";
            }
        }
        pictureValue += "]";
        result.put("pictureData", JSON.parseArray(pictureValue));
        String sql = "from LvAttachmentComboOfTourismModel where fkTourismModelId='" + id + "' and type!='2' order by status desc,addTime asc";
        List<LvAttachmentComboOfTourismModel> lvAttachmentComboOfTourismList = lvAttachmentComboOfTourismModelDao.listQuery(sql);
        String attachmentValue = "[";
        for (int i = 0; i < lvAttachmentComboOfTourismList.size(); i++) {
            LvAttachmentComboOfTourismModel lvAttachmentComboOfTourismModel = lvAttachmentComboOfTourismList.get(i);
            if (i != lvAttachmentComboOfTourismList.size() - 1) {
                attachmentValue += "{\"id\":\"" + lvAttachmentComboOfTourismModel.getFkAttachmentId() + "\",\"type\":\"" + lvAttachmentComboOfTourismModel.getType() + "\",\"text\":\"" + lvAttachmentComboOfTourismModel.getComment() + "\"},";
            } else {
                attachmentValue += "{\"id\":\"" + lvAttachmentComboOfTourismModel.getFkAttachmentId() + "\",\"type\":\"" + lvAttachmentComboOfTourismModel.getType() + "\",\"text\":\"" + lvAttachmentComboOfTourismModel.getComment() + "\"}";
            }
        }
        attachmentValue += "]";
        result.put("attachmentData", JSON.parseArray(attachmentValue));
        return result;
    }

    /**
     * 获取旅游模板及其从当前时间往后的在售旅游
     * @param id 旅游模板id
     * @return
     */
    public HashMap<String, Object> getModelAndForSaleById(String id) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        Date now=new Date();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(now);
        int intMonth=calendar.get(Calendar.MONTH)+1;
        String month=intMonth>10?(""+intMonth):("0"+intMonth);
        String startDate=calendar.get(Calendar.YEAR)+"-"+month+"-"+"01";
        String endDate=calendar.get(Calendar.YEAR)+"-"+month+"-"+"31";
        LvTourismModel lvTourismModel = lvTourismModelDao.get(id);
        result.put("lvTourismModel", lvTourismModel);
        String sql="select * from lv_tourism_for_sale where fk_tourism_model_id='"+id+"' and server_date>='"+startDate+"' and server_date<='"+endDate+"'";
        List<LvTourismForSale> lvTourismForSaleList=lvTourismForSaleDao.search(sql);
        result.put("lvTourismForSaleList", lvTourismForSaleList);
        return result;
    }

    /**
     * 获取旅游模板及其指定时间范围内在售旅游
     * @param id 旅游模板id
     * @param year 年
     * @param month 月
     * @return
     */
    public HashMap<String, Object> getModelForSaleByIdAndMonth(String id,String year,String month) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        String startDate=year+"-"+month+"-"+"01";
        String endDate=year+"-"+month+"-"+"31";
        String sql="select * from lv_tourism_for_sale where fk_tourism_model_id='"+id+"' and server_date>='"+startDate+"' and server_date<='"+endDate+"'";
        List<LvTourismForSale> lvTourismForSaleList=lvTourismForSaleDao.search(sql);
        String stringList = "[";
        for (int i = 0; i < lvTourismForSaleList.size(); i++) {
            LvTourismForSale lvTourismForSale = lvTourismForSaleList.get(i);
            String element = "{\"id\":\"" + lvTourismForSale.getId()
                    + "\",\"adultSeatNumber\":\"" + lvTourismForSale.getAdultSeatNumber()
                    + "\",\"childSeatNumber\":\"" + lvTourismForSale.getChildSeatNumber()
                    + "\",\"saledAdultSeatNumber\":\"" + lvTourismForSale.getSaledAdultSeatNumber()
                    + "\",\"saledChildSeatNumber\":\"" +lvTourismForSale.getSaledChildSeatNumber()
                    + "\",\"serverDate\":\"" + (lvTourismForSale.getServerDate() == null ? "" : DATE_FORMAT.format(lvTourismForSale.getServerDate()))
                    + "\",\"status\":\"" + (lvTourismForSale.getStatus() == null ? "" : lvTourismForSale.getStatus() == 0 ? 1 : 3)
                    + "\",\"price\":\"" +(lvTourismForSale.getMinPrice() == null ? "" : lvTourismForSale.getMinPrice())
                    + "\",\"isModifyPriceCombo\":\"" + lvTourismForSale.getIsModifyPriceCombo()
                    + "\",\"fkTourismModelId\":\"" + lvTourismForSale.getFkTourismModelId()
                    + "\",\"fkTransportId\":\"" + lvTourismForSale.getFkTransportId()
                    + "\",\"tourismName\":\"" + lvTourismForSale.getTourismName()
                    + "\",\"allowIncreaseGuestRoom\":\"" + lvTourismForSale.getAllowIncreaseGuestRoom()
                    + "\",\"guestRoomPrice\":\"" + lvTourismForSale.getGuestRoomPrice()+ "\"}";
            stringList += element;
            if (i != lvTourismForSaleList.size() - 1) {
                stringList += ",";
            }
        }
        stringList += "]";
        JSONArray jsonList = JSON.parseArray(stringList);
        result.put("lvTourismForSaleList", jsonList);
        return result;
    }
    /**
     * 获取旅游模板及其价格套餐
     * @param id 旅游模板id
     * @return
     */
    public HashMap<String, Object> getModelAndPriceById(String id) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        LvTourismModel lvTourismModel = lvTourismModelDao.get(id);
        result.put("lvTourismModel", lvTourismModel);
        List<LvPriceComboOfTourismModel> lvPriceComboOfTourismModelList = lvPriceComboOfTourismModelDao.findBy("fkTourismModelId", id);
        int count = 0;
        String priceComboValue = "[";
        for (int i = 0; i < lvPriceComboOfTourismModelList.size(); i++) {
            LvPriceComboOfTourismModel lvPriceComboOfTourismModel = lvPriceComboOfTourismModelList.get(i);
            if (count == lvPriceComboOfTourismModelList.size()) {
                priceComboValue += "{\"title\":\"" + (lvPriceComboOfTourismModel.getTitle() == null ? "" : lvPriceComboOfTourismModel.getTitle())
                        + "\"," + "\"comment\":\"" + (lvPriceComboOfTourismModel.getComment() == null ? "" : lvPriceComboOfTourismModel.getComment())
                        + "\"," + "\"sequence\":\"" + (lvPriceComboOfTourismModel.getSequence() == null ? "" : lvPriceComboOfTourismModel.getSequence())
                        + "\"," + "\"adultPrice\":\"" + (lvPriceComboOfTourismModel.getAdultPrice() == null ? "" : lvPriceComboOfTourismModel.getAdultPrice())
                        + "\"," + "\"childPrice\":\"" + (lvPriceComboOfTourismModel.getChildPrice() == null ? "" : lvPriceComboOfTourismModel.getChildPrice()) + "\"},";
            } else {
                priceComboValue += "{\"title\":\"" + (lvPriceComboOfTourismModel.getTitle() == null ? "" : lvPriceComboOfTourismModel.getTitle())
                        + "\"," + "\"comment\":\"" + (lvPriceComboOfTourismModel.getComment() == null ? "" : lvPriceComboOfTourismModel.getComment())
                        + "\"," + "\"sequence\":\"" + (lvPriceComboOfTourismModel.getSequence() == null ? "" : lvPriceComboOfTourismModel.getSequence())
                        + "\"," + "\"adultPrice\":\"" + (lvPriceComboOfTourismModel.getAdultPrice() == null ? "" : lvPriceComboOfTourismModel.getAdultPrice())
                        + "\"," + "\"childPrice\":\"" + (lvPriceComboOfTourismModel.getChildPrice() == null ? "" : lvPriceComboOfTourismModel.getChildPrice()) + "\"}";
            }
            count++;
        }
        priceComboValue += "]";
        result.put("priceComboData", JSON.parseArray(priceComboValue));
        return result;
    }

    /**获取某页的旅游模板列表
     * @param pageNumber 第几页
     * @param pageSize 每页大小
     * @param tourismName 景点名称
     * @param status 状态：0.未审核1.审核通过2.审核未通过3.发布4.待停售5.停售
     * @return
     */
    public List<LvTourismModel> getList(String pageNumber, String pageSize, String tourismName,String status) {
        String sql = "select * from lv_tourism_model where 1=1";
        int startIndex = 0;
        int endIndex = Integer.parseInt(pageSize);
        if (tourismName != null&& !"".equals(tourismName)) {
            sql += " and tourism_name like '%" + tourismName + "%'";
        }
        if(status!=null&&!"".equals(status)){
            String[] statusArray=status.split(",");
            String statusSql="(";
            for(int i=0;i<statusArray.length;i++){
                if(i==0){
                    statusSql+=" status='"+statusArray[i]+"'";
                }else{
                    statusSql+=" or status='"+statusArray[i]+"'";
                }
            }
            statusSql+=")";
            if(!"()".equals(statusSql)){
                sql+=" and "+statusSql;
            }
        }
        sql += " order by case when modify_time is null then add_time else modify_time end desc";
        if (pageNumber == null) {
            pageNumber = "0";
        } else {
            int number = Integer.parseInt(pageNumber);
            if (!"0".equals(pageNumber)) {
                number = number - 1;
            }
            startIndex = (number) * Integer.parseInt(pageSize);
        }
        sql += " limit " + startIndex + "," + endIndex;
        List<LvTourismModel> list = lvTourismModelDao.search(sql);
        return list;
    }

    /**
     * 根据id获取旅游模板
     * @param id 旅游模板id
     * @return
     */
    public LvTourismModel get(String id) {
        LvTourismModel lvTourismModel = lvTourismModelDao.get(id);
        return lvTourismModel;
    }

    /**
     * 修改
     * @param lvTourismModel 旅游模板对象
     * @return
     */
    public String update(LvTourismModel lvTourismModel) {
        String result = lvTourismModelDao.update(lvTourismModel);
        if ("0".equals(result)) {
            return "0";
        }
        return "1";
    }

    /**
     * 统计旅游模板数目
     * @param tourismName 景点名称
     * @param status 状态：0.未审核1.审核通过2.审核未通过3.发布4.待停售5.停售
     * @return
     */
    public int getCount(String tourismName,String status) {
        String sql = "select * from lv_tourism_model where 1=1";
        if (tourismName != null && !"".equals(tourismName)) {
            sql += " and tourism_name like '%" + tourismName + "%'";
        }
        if(status!=null&&!"".equals(status)){
            String[] statusArray=status.split(",");
            String statusSql="(";
            for(int i=0;i<statusArray.length;i++){
                if(i==0){
                    statusSql+=" status='"+statusArray[i]+"'";
                }else{
                    statusSql+=" or status='"+statusArray[i]+"'";
                }
            }
            statusSql+=")";
            if(!"()".equals(statusSql)){
                sql+=" and "+statusSql;
            }
        }
        sql += " order by case when modify_time is null then add_time else modify_time end desc";
        int count = lvTourismModelDao.getSqlSumQuery(sql);
        return count;
    }

    /**
     * 发布
     * @param id 旅游模板id
     * @return
     */
    public String publish(String id) {
        LvTourismModel lvTourismModel = lvTourismModelDao.get(id);
        lvTourismModel.setStatus(3);
        return lvTourismModelDao.update(lvTourismModel);
    }

    /**
     * 取消
     * @param id 旅游模板id
     * @return
     */
    public String cancel(String id) {
        String sql = "delete from lv_tourism_for_sale where id='"+id+"'";
        return lvTourismForSaleDao.delete(sql);
    }

    /**
     * 修改滚动图片
     * @param modelId 旅游模板id
     * @param pictureData 滚动图片json字符串
     * @param userId 用户id
     * @return
     */
   public String updatePicture(String modelId, String pictureData, String userId) {
       Date now = new Date();
       lvAttachmentComboOfTourismModelDao.delete(null,modelId);
       JSONArray pictureArray = JSON.parseArray(pictureData);
       if (pictureArray != null) {
           for (int i = 0; i < pictureArray.size(); i++) {
               JSONObject object = pictureArray.getJSONObject(i);
               String attachmentId = object.getString("id");
               LvAttachmentComboOfTourismModel lvAttachmentComboOfTourismModel = new LvAttachmentComboOfTourismModel();
               lvAttachmentComboOfTourismModel.setSequence(i);
               lvAttachmentComboOfTourismModel.setFkTourismModelId(modelId);
               lvAttachmentComboOfTourismModel.setComment("");
               lvAttachmentComboOfTourismModel.setFkAttachmentId(attachmentId);
               lvAttachmentComboOfTourismModel.setType(2);
               lvAttachmentComboOfTourismModel.setAddTime(now);
               lvAttachmentComboOfTourismModel.setFkAddUserId(userId);
               lvAttachmentComboOfTourismModel.setStatus(0);
               lvAttachmentComboOfTourismModelDao.save(lvAttachmentComboOfTourismModel);
               Attachment attachmentObject = attachmentManager.get(attachmentId);
               attachmentObject.setBusinessId(modelId);
               attachmentObject.setWorkItem("rollingPicture");
               attachmentManager.update(attachmentObject);
           }
       }
       return "1";
   }

    /**
     * 修改附件
     * @param modelId 旅游模板id
     * @param attachmentData 附件json字符串
     * @param userId 用户id
     * @return
     */
   public String updateAttachment(String modelId, String attachmentData, String userId) {
       Date now = new Date();
       lvAttachmentComboOfTourismModelDao.delete(null,modelId);
       JSONArray attachmentArray = JSON.parseArray(attachmentData);
       if (attachmentArray != null) {
           for (int i = 0; i < attachmentArray.size(); i++) {
               JSONObject object = attachmentArray.getJSONObject(i);
               LvAttachmentComboOfTourismModel lvAttachmentComboOfTourismModel = new LvAttachmentComboOfTourismModel();
               lvAttachmentComboOfTourismModel.setSequence(i);
               lvAttachmentComboOfTourismModel.setFkTourismModelId(modelId);
               if (object.getInteger("type") == 0) {
                   lvAttachmentComboOfTourismModel.setComment(object.getString("text"));
                   lvAttachmentComboOfTourismModel.setFkAttachmentId(object.getString("id"));
                   lvAttachmentComboOfTourismModel.setType(0);
               } else {
                   lvAttachmentComboOfTourismModel.setComment(object.getString("text"));
                   lvAttachmentComboOfTourismModel.setFkAttachmentId("");
                   lvAttachmentComboOfTourismModel.setType(1);
               }
               lvAttachmentComboOfTourismModel.setAddTime(now);
               lvAttachmentComboOfTourismModel.setFkAddUserId(userId);
               lvAttachmentComboOfTourismModel.setStatus(0);
               lvAttachmentComboOfTourismModelDao.update(lvAttachmentComboOfTourismModel);
               if (object.getInteger("type") == 0) {
                   Attachment attachmentObject = attachmentManager.get(object.getString("id"));
                   attachmentObject.setWorkItem("attachmentPicture");
                   attachmentObject.setBusinessId(modelId);
                   attachmentObject.setFilePath(modelId);
                   attachmentManager.update(attachmentObject);
               }
           }
       }
       return "1";
   }

    /**
     * 删除旅游模板及其在售旅游
     * @param id 旅游模板id
     * @return
     */
    public String delete(String id) {
        Attachment attachment=new Attachment();
        attachment.setBusinessId(id);
        attachmentManager.deleteAttachment(attachment);
        String deleteAttachment=lvAttachmentComboOfTourismModelDao.delete(null,id);
        if("0".equals(deleteAttachment)){
            return  "0";
        }
        String deletePrice=lvPriceComboOfTourismModelDao.delete(null,id);
        List<LvTourismForSale> lvTourismForSaleList=lvTourismForSaleDao.findBy("fkTourismModelId",id);
        for(int i=0;i<lvTourismForSaleList.size();i++){
            LvTourismForSale lvTourismForSale=lvTourismForSaleList.get(i);
            String deletePriceModifyResult=lvPriceComboOfTourismForModifyDao.delete(null,lvTourismForSale.getId());
            if("0".equals(deletePriceModifyResult)){
                return "0";
            }
            String sql="delete from lv_tourism_for_sale where id='"+lvTourismForSale.getId()+"'";
            String deleteTourismForSale=lvTourismForSaleDao.delete(sql);
            if("0".equals(deleteTourismForSale)){
                return "0";
            }
        }
        String result=lvTourismModelDao.delete(id,null);
        if("0".equals(result)){
            return "0";
        }
        return "1";
    }

    /**
     * 取消停售
     * @param id 旅游模板id
     * @param autoArrangeEndDate 自动排班截止日期
     * @param userId 用户id
     * @return
     */
    public String quitStopSell(String id, String autoArrangeEndDate,String userId) {
        Date now=new Date();
        LvTourismModel lvTourismModel = lvTourismModelDao.get(id);
        if(autoArrangeEndDate!=null&&!"".equals(autoArrangeEndDate)){
            try{
                Date autoDate=DATE_FORMAT.parse(autoArrangeEndDate);
                if(lvTourismModel.getAutoArrangeEndDate()!=null){
                    if(autoDate.getTime()<=lvTourismModel.getAutoArrangeEndDate().getTime()){
                        List<LvTourismForSale> lvTourismForSaleList=lvTourismForSaleManager.search(id,autoDate,"0");
                        for (int i = 0; i < lvTourismForSaleList.size(); i++) {
                            LvTourismForSale lvTourismForSale = lvTourismForSaleList.get(i);
                            lvTourismForSale.setStatus(1);
                            lvTourismForSale.setFkModifyUserId(userId);
                            lvTourismForSale.setModifyTime(now);
                            lvTourismForSaleManager.update(lvTourismForSale);
                        }
                    }
                }else{
                    List<LvTourismForSale> lvTourismForSaleList=lvTourismForSaleManager.search(id,autoDate,"0");
                    for (int i = 0; i < lvTourismForSaleList.size(); i++) {
                        LvTourismForSale lvTourismForSale = lvTourismForSaleList.get(i);
                        lvTourismForSale.setStatus(1);
                        lvTourismForSale.setFkModifyUserId(userId);
                        lvTourismForSale.setModifyTime(now);
                        lvTourismForSaleManager.update(lvTourismForSale);
                    }
                }
                lvTourismModel.setAutoArrangeEndDate(autoDate);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            lvTourismModel.setAutoArrangeEndDate(null);
        }
        lvTourismModel.setFkModifyUserId(userId);
        lvTourismModel.setModifyTime(now);
        lvTourismModel.setStatus(3);
        return lvTourismModelDao.update(lvTourismModel);
    }
}
